using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.IO;
using Adge.Common;

namespace Adge.Web
{
    public class CompressedViewStatePage : System.Web.UI.Page
    {
        protected override void SavePageStateToPersistenceMedium(object state)
        {
            Pair pair;
            PageStatePersister persister = this.PageStatePersister;
            object viewState;
            if (state is Pair)
            {
                pair = (Pair)state;
                persister.ControlState = pair.First;
                viewState = pair.Second;
            }
            else
            {
                viewState = state;
            }

            LosFormatter formatter = new LosFormatter();
            StringWriter writer = new StringWriter();
            formatter.Serialize(writer, viewState);
            string viewStateStr = writer.ToString();
            byte[] data = Convert.FromBase64String(viewStateStr);
            byte[] compressedData = CompressHelper.Compress(data);
            string str = Convert.ToBase64String(compressedData);

            persister.ViewState = str;
            persister.Save();
        }

        protected override object LoadPageStateFromPersistenceMedium()
        {
            PageStatePersister persister = this.PageStatePersister;
            persister.Load();

            string viewState = persister.ViewState.ToString();
            byte[] data = Convert.FromBase64String(viewState);
            byte[] uncompressedData = CompressHelper.DeCompress(data);
            string str = Convert.ToBase64String(uncompressedData);
            LosFormatter formatter = new LosFormatter();
            return new Pair(persister.ControlState, formatter.Deserialize(str));
        }
    }
}
